<template>
  <div class="auto-matching-container">
    <div class="page-header">
      <div class="page-title">漏洞自动匹配</div>
    </div>

    <!-- 资产信息表单 -->
    <el-card class="asset-info-card">
      <template #header>
        <div class="card-header">资产信息</div>
      </template>
      <el-form :model="assetForm" label-width="80px" :disabled="isMatching">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="漏洞标题">
              <el-input
                v-model="assetForm.title"
                placeholder="请输入漏洞标题"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="软件名称">
              <el-input
                v-model="assetForm.product"
                placeholder="请输入软件名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="漏洞类型">
              <el-select
                v-model="assetForm.vuln_type"
                placeholder="请选择漏洞类型"
                clearable
              >
                <el-option
                  v-for="item in vulnTypeList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="漏洞描述">
              <el-input
                v-model="assetForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入漏洞描述"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="12"
            style="
              display: flex;
              flex-direction: column;
              justify-content: space-between;
            "
          >
            <!-- 匹配配置区域 -->
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <el-radio-group
                v-model="assetForm.mode"
                @change="handleMatchingTypeChange"
              >
                <el-radio-button :label="0">模糊匹配</el-radio-button>
                <el-radio-button :label="1">精确匹配</el-radio-button>
              </el-radio-group>
              <el-button
                type="primary"
                icon="Search"
                @click="startMatching"
                :loading="isMatching"
                >开始匹配</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 匹配进度 -->
    <div v-if="isMatching" class="matching-progress-container">
      <div class="progress-title">匹配进度</div>
      <div class="progress-info">正在进行漏洞匹配...</div>
      <el-progress :percentage="matchingProgress" :stroke-width="8" />
    </div>

    <!-- 匹配结果 -->
    <div v-if="matchingResult.length" class="matching-result-container">
      <div class="result-header">
        <div class="result-title">匹配结果</div>
        <div class="page-actions">
          <el-button
            icon="Download"
            @click="handleExportResult"
            :disabled="!selectedRows.length"
            plain
            type="primary"
            >导出结果</el-button
          >
          <div class="result-summary">
            共找到 {{ total }} 个匹配漏洞，当前显示
            {{ matchingResult.length }} 条
          </div>
        </div>
      </div>


      <VulnTable
        :tableData="matchingResult"
        :loading="isMatching"
        @selection-change="handleSelectionChange"
      >
        <template #optSlot>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                icon="View"
                @click="handleViewDetails(row)"
                >查看详情</el-button
              >
            </template>
          </el-table-column>
        </template>
      </VulnTable>

      <div v-if="total > 0" class="pagination-container">
        <el-pagination
          background
          v-model:current-page="page"
          v-model:page-size="limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePagination"
          @current-change="handlePagination"
        />
      </div>
    </div>

    <!-- 无匹配结果提示 -->
    <el-empty
      v-if="matchingCompleted && !matchingResult.length"
      description="未找到匹配漏洞"
    >
      <template #image>
        <el-icon class="empty-icon">
          <Search />
        </el-icon>
      </template>
      <el-button type="primary" @click="startMatching">重新匹配</el-button>
    </el-empty>

    <!-- 漏洞详情弹窗 -->
    <VulnDetailDialog
      v-model="detailVisible"
      :vuln-data="currentVulnData"
      @closed="handleDetailClosed"
    />
  </div>
</template>

<script setup>
import { getVulnMatchRecords, getVulnMatchDetail } from "@/api/vulnMatch.js";
import { downloadFileFromResponse } from "@/utils/fileOpt.js";
import VulnDetailDialog from "@/components/vulnDetailDialog/index.vue";
import VulnTable from "@/components/vulnTable/index.vue";

import { useCommonStore } from "@/stores/common";
const store = useCommonStore();
const vulnTypeList = computed(() => store.vulnTypeList);

// 匹配状态
const isMatching = ref(false);
const matchingProgress = ref(0);
const matchingCompleted = ref(false);
const total = ref(0);
const page = ref(1);
const limit = ref(10);

// 资产信息表单
const assetForm = reactive({
  page_index: 1,
  page_size: 10,
  mode: 0,
});

// 匹配结果
const matchingResult = ref([]);
const selectedRows = ref([]);

// 详情弹窗相关
const detailVisible = ref(false);
const currentVulnData = ref({});

// 获取标签类型
const getTagType = (level) => {
  const typeMap = {
    高危: "danger",
    中危: "warning",
    低危: "warning",
  };
  return typeMap[level] || "";
};

// 处理选中行
const handleSelectionChange = (selection) => {
  selectedRows.value = selection.map((item) => item.id);
};

// 处理匹配类型变更
const handleMatchingTypeChange = (type) => {
  assetForm.mode = type;
};

// 获取匹配结果
const fetchMatchResults = async () => {
  // 重置选中行
  isMatching.value = true;
  matchingProgress.value = 0;

  try {
    // 进度条模拟
    const progressInterval = setInterval(() => {
      if (matchingProgress.value < 90) {
        matchingProgress.value += 10;
      }
    }, 200);

    const res = await getApiVulnMatchRecords();

    // 清除进度条定时器
    clearInterval(progressInterval);
    matchingProgress.value = 100;

    // 处理返回数据
    matchingResult.value = res.data || [];
    total.value = res.total_items || 0;

    setTimeout(() => {
      isMatching.value = false;
      matchingCompleted.value = true;

      if (matchingResult.value.length > 0) {
        ElMessage.success(`共找到 ${total.value} 个匹配漏洞`);
      } else {
        ElMessage.info("未找到匹配漏洞");
      }
    }, 500);
  } catch (error) {
    console.error("匹配失败:", error);
    ElMessage.error("漏洞匹配失败，请稍后重试");
    isMatching.value = false;
  }
};

const getApiVulnMatchRecords = () => {
  // 调用API
  const params = {
    title: assetForm.title,
    vuln_type: assetForm.vuln_type,
    description: assetForm.description,
    page_index: page.value,
    page_size: limit.value,
    mode: assetForm.mode,
    product: assetForm.product,
  };

  return getVulnMatchRecords(params);
};

// 开始匹配
const startMatching = () => {
  // 重置页码
  assetForm.page_index = 1;
  // 开始匹配
  fetchMatchResults();
};

// 处理分页
const handlePagination = () => {
  fetchMatchResults();
};

// 查看详情
const handleViewDetails = (row) => {
  currentVulnData.value = row;
  detailVisible.value = true;
};

// 详情弹窗关闭
const handleDetailClosed = () => {
  currentVulnData.value = {};
};

// 导出结果
const handleExportResult = async () => {
  try {
    if (!matchingResult.value.length) {
      ElMessage.warning("没有可导出的数据");
      return;
    }

    const data = {
      id_list: selectedRows.value,
    };
    const res = await getVulnMatchDetail(data);

    // 下载文件
    downloadFileFromResponse(res);

    ElMessage.success("匹配结果导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("匹配结果导出失败");
  }
};
</script>

<style lang="scss" scoped>
.auto-matching-container {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 20px;
      font-weight: bold;
      color: var(--text-color);
    }
  }

  .asset-info-card {
    margin-bottom: 20px;

    .card-header {
      font-weight: bold;
    }
  }

  .page-actions {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 10px;
  }

  .matching-progress-container {
    background-color: var(--card-bg);
    padding: 20px;
    border-radius: 4px;
    box-shadow: var(--box-shadow-light);
    margin-bottom: 20px;

    .progress-title {
      font-weight: bold;
      margin-bottom: 10px;
    }

    .progress-info {
      color: var(--text-color-secondary);
      margin-bottom: 15px;
    }
  }

  .matching-result-container {
    margin-top: 20px;

    .result-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .result-title {
        font-size: 16px;
        font-weight: bold;
      }

      .result-summary {
        margin: 0 20px;
        color: var(--text-color-secondary);
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .empty-icon {
    font-size: 60px;
    color: var(--text-color-secondary);
  }
}
</style>
